package com.wz.datachannel.view;

import java.io.File;
import java.util.ArrayList;

import com.alibaba.fastjson.JSONObject;
import com.wz.datachannel.R;
import com.wz.datachannel.model.UserInfo;
import com.wz.datachannel.netty.WzDataChannelHelper;
import com.wz.datachannel.netty.WzDataChannelHelper.ICallBackUpdateUserInfo;
import com.wz.datachannel.netty.WzDataChannelHelper.SerConnStatus;
import com.wz.datachannel.service.MainService;
import com.wz.datachannel.util.ToastUtil;
import com.wz.datachannel.util.ViewUtil;
import com.wzfile.upload.WzUpload;
import com.wzfile.upload.WzUpload.OnUploadListener;
import com.wzfile.upload.WzUpload.RequestDownCardResult;
import com.wzfile.upload.WzUpload.UpLoadKeyErrorException;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

public class UpdateStActivity extends BaseActivity implements OnClickListener {

	private PhotoEditView mPhotoEditView;
	private View mLoadingLayout;
	private View mHintView;
	private Button mTakePhoto_btn;
	private Button mConfirm_btn;

	private String uploadkey = null;
	private UserInfo userInfo = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		WzDataChannelHelper dataChannel = MainService.getDataChannel();
		if (dataChannel != null && dataChannel.getConnStatus() == SerConnStatus.LOGIN_OK) {
			//已登录
			userInfo = dataChannel.getUserInfo();
			if (userInfo == null) {
				showToastText("用户信息无效！");
				finish();
				return;
			}
			uploadkey = dataChannel.getFileUploadKey();
			if (uploadkey == null) {
				showToastText("上传服务无法启动！");
				finish();
				return;
			}
		} else {
			//未登录
			finish();
			return;
		}
		overridePendingTransition(R.anim.fade_in2, R.anim.fade_out2);
		//当前已成功登录:		
		setContentView(R.layout.activity_update_st);

		if (getIntent().getStringExtra("uploadkey") != null) {
			uploadkey = getIntent().getStringExtra("uploadkey");
		}

		mPhotoEditView = (PhotoEditView) findViewById(R.id.stUpdate_photoEditView);
		mLoadingLayout = findViewById(R.id.stUpdate_loadingLayout);
		mHintView = findViewById(R.id.stUpdate_hint_tv);
		mTakePhoto_btn = (Button) findViewById(R.id.stUpdate_takePhoto_btn);
		mConfirm_btn = (Button) findViewById(R.id.stUpdate_confirm_btn);
		mTakePhoto_btn.setOnClickListener(this);
		mConfirm_btn.setOnClickListener(this);

		mPhotoEditView.setVisibility(View.INVISIBLE);

		new File(Environment.getExternalStorageDirectory().getPath() + "/temp/").mkdirs();
	}

	@Override
	public void finish() {
		super.finish();
	}

	@Override
	protected void onDestroy() {
		if (null != mPhotoEditView) {
			mPhotoEditView.close();
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		try {
			switch (v.getId()) {
			case R.id.stUpdate_confirm_btn:
				startUpdatePhoto();
				break;
			case R.id.stUpdate_takePhoto_btn:
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				i.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_capture.jpg")));
				startActivityForResult(i, 2);
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean isupdatephoto = false;

	private void startUpdatePhoto() {

		if (isupdatephoto)
			return;

		if (!mPhotoEditView.isOpen()) {
			showToastText("请先选择要使用的图片!");
			return;
		}
		String filename = Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_photo.jpg";
		if (!mPhotoEditView.takeImageToFile(filename)) {
			//截取头像失败，请选择文件
			showToastText("提取头像出错，请重新选择图片!");
			return;
		}

		ViewUtil.showView(mLoadingLayout);
		isupdatephoto = true;

		try {
			WzUpload upload = WzUpload.getUpload(uploadkey);

			upload.setOnUploadListener(new OnUploadListener() {

				@Override
				public void OnUpload(String arg0, long arg1) {
				}

				@Override
				public void OnSucess(String arg0, RequestDownCardResult arg1) {
					//上传成功
					try {
						updateUserPhotoInfo(arg1.getFileList()[0].getFileAddr());
					} catch (Exception e) {
						showToastText("上传头像时发生错误，请稍后重试!");
						gotoContent();
					}
				}

				@Override
				public void OnStop(String arg0, int arg1, String arg2) {
					showToastText("头像上传失败:" + arg2);
					gotoContent();
				}

				@Override
				public void OnStart(String arg0, int arg1) {
				}

				@Override
				public void OnProgress(String arg0, int arg1, long arg2, long arg3) {
				}

				@Override
				public void OnLoading(String arg0) {
				}
			});

			ArrayList<File> files = new ArrayList<File>();
			files.add(new File(filename));
			upload.start(files, "upload");

		} catch (UpLoadKeyErrorException e) {
			showToastText("操作失败,请稍后再试.");
			gotoContent();
		}

	}

	private void updateUserPhotoInfo(String url) {
		//此处添加用户资料的处理过程:
		WzDataChannelHelper dataChannel = MainService.getDataChannel();
		if (dataChannel != null && dataChannel.getConnStatus() == SerConnStatus.LOGIN_OK) {
			JSONObject params = new JSONObject();
			params.put("photo", url);
			final Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 1:
						sucess();
						break;
					case 0:
						showToastText("修改资料失败：" + msg);
						gotoContent();
						break;
					case -1:
						showToastText("请求处理超时，请稍后重试！");
						gotoContent();
						break;
					}
				}
			};

			if (dataChannel.updateUserInfo(params.toJSONString(), new ICallBackUpdateUserInfo() {

				@Override
				public void OnTimeOut() {
					handler.sendEmptyMessage(-1);
				}

				@Override
				public void OnSucess() {
					handler.sendEmptyMessage(1);
				}

				@Override
				public void OnFail(String msg) {
					Message m = new Message();
					m.what = 0;
					m.obj = msg;
					handler.sendMessage(m);
				}

			}) != 1) {
				//请求失败:
				showToastText("请稍后重试！");
				gotoContent();
			}

		} else {
			showToastText("您已下线，请上线后再试！");
			gotoContent();
		}

	}

	private void sucess() {
		showToastText("修改头像成功！");
		finish();
	}

	private void gotoContent() {
		ViewUtil.hideView(mLoadingLayout);
		isupdatephoto = false;
	}

	private void showToastText(String text) {
		ToastUtil.toastShowLong(getApplication(), text);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			switch (requestCode) {
			case 1: {
				//选择图片
				if (resultCode == RESULT_OK) {
					String name = data.getDataString();
					Uri uri = Uri.parse(name);
					String filename = "";
					if (!name.startsWith("file:///")) {
						String[] proj = { MediaStore.Images.Media.DATA };
						@SuppressWarnings("deprecation")
						Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
						int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						actualimagecursor.moveToFirst();
						filename = actualimagecursor.getString(actual_image_column_index);
					} else {
						filename = name;
						try {
							filename = name.substring(name.lastIndexOf("///") + 2);
						} catch (Exception e) {
						}
					}
					mPhotoEditView.openImageFile(filename);
				}
				break;
			}
			case 2: {
				//拍照  
				if (resultCode == RESULT_OK) {
					mPhotoEditView.openImageFile(Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_capture.jpg");
					new File(Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_capture.jpg").delete();
				}
				break;
			}
			}

		} catch (Exception e) {
			;
		}
	}

}
